import path from "path";
import {
  createClassGoods,
  updateClassGoods,
  getClassGoods,
  deleteClassGoods,
} from "../service/goods.service.js";
export async function uploadGoods(ctx, next) {
  const { file } = ctx.request.files;
  //
  if (file) {
    ctx.body = {
      code: 200,
      message: "上传成功",
      result: {
        url: path.basename(file.filepath),
      },
    };
  } else {
    return ctx.app.emit(
      "error",
      {
        code: 10001,
        message: "上传失败",
        result: "",
      },
      ctx
    );
  }

  next();
}
export async function createdGoods(ctx, next) {
  const { name, price, inventory, pic, desc } = ctx.request.body;

  try {
    const res = await createClassGoods({ name, price, inventory, pic, desc });

    ctx.body = {
      code: 200,
      message: "创建成功",
      result: res,
    };
  } catch (error) {
    return ctx.app.emit(
      "error",
      {
        code: 10001,
        message: "创建失败",
        result: "",
      },
      ctx
    );
  }

  await next();
}

export async function updateGoods(ctx, next) {
  const id = ctx.params.id;
  const data = ctx.request.body;

  try {
    const res = await updateClassGoods(id, data);

    if (res) {
      ctx.body = {
        code: 200,
        message: "更新成功",
        result: res,
      };
    } else {
      return ctx.app.emit(
        "error",
        {
          code: 10001,
          message: "更新失败商品不存在",
          result: "",
        },
        ctx
      );
    }
  } catch (error) {
    return ctx.app.emit(
      "error",
      {
        code: 10001,
        message: "更新失败",
        result: "",
      },
      ctx
    );
  }
  await next();
}

export async function getGoodsList(ctx, next) {
  const page = ctx.query.page || 1;
  const pageSize = ctx.query.pageSize || 10;
  const name = ctx.query.name;
  const inventory = ctx.query.inventory;
  try {
    const res = await getClassGoods(page, pageSize, name, inventory);
    ctx.body = {
      code: 200,
      message: "获取商品列表成功",
      result: res,
    };
  } catch (error) {
    return ctx.app.emit("error", {
      code: 10001,
      message: "获取商品列表失败",
      result: "",
    });
  }
}

export async function deleteGoods(ctx, next) {
  const id = ctx.params.id;
  try {
    const res = await deleteClassGoods(id);

    if (res) {
      ctx.body = {
        code: 200,
        message: "删除成功",
        result: res,
      };
    }
  } catch (error) {
    return ctx.app.emit("error", {
      code: 10001,
      message: "删除失败",
      result: "",
    });
  }
}
